<template>
  <div class="login">
    <el-row :gutter="10" type="flex" justify="center" align="middle">
      <el-col :xs="14" :sm="12" :md="10" :lg="8" :xl="6">
        <el-form :model="loginForm" :rules="rules" status-icon label-position="top" ref="loginForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">登录</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async submitForm (formName) {
      try {
        // await 后的promise对象返回执行后的then或者catch  如果是then继续往下执行，如果是catch报错
        await this.$refs.loginForm.validate()
        const res = await this.axios.post('/login', this.loginForm)
        const {data: {meta: {msg, status}}} = res
        if (status === 200) {
          // 登录成功
          this.$message({
            message: msg,
            type: 'success',
            duration: 2000
          })
          localStorage.setItem('token', res.data.data.token)
          this.$router.push('/')
        } else {
          // 登录失败
          this.$message({
            message: msg,
            type: 'error',
            duration: 2000
          })
        }
      } catch (e) {
        console.log(e)
      }
    },
    resetForm () {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style lang="less">
  .login {
    height: 100%;
    .el-row {
      height: 100%;
      background-color: rgb(65, 79, 85);
      .el-col {
        background-color: #fff;
        border-radius: 20px;
      }
    }
    form {
      padding: 20px;
    }
  }
</style>
